<template>
	<div class="page-common-layout" :key="id">
		<div class="page-common-content">
			<tool-bar
			  @search="search"
			  @reset="resetSearch"
			>
			  <template v-if="formType !== 'viewData'" slot="toolBtn" slot-scope="scope">
					<span v-for="(item, index) in topButtonList" :key="index">
						<template v-if="item.permissionId">
							<a-button
								v-if="item.checked && item.btnType != 'search'"
								:class="item.btnStyle"
								:icon="item.icon"
								@click="handleBtnEvent(item, $refs.table.rows)"
								v-action="item.permissionId"
							>{{item.name}}</a-button>
							<combined-query
								v-if="item.checked && item.btnType == 'search'"
								v-action="item.permissionId"
								:columns="columns"
								@refresh="(e) => {
									queryParam.advanceFilter = e, $refs.table.refresh(true)
								}"
							/>
						</template>
						<template v-else>
							<a-button
								v-if="item.checked && item.btnType != 'search'"
								:class="item.btnStyle"
								:icon="item.icon"
								@click="handleBtnEvent(item, $refs.table.rows)"
							>{{item.name}}</a-button>
							<combined-query v-if="item.checked && item.btnType == 'search'" :columns="columns" @refresh="(e) => {queryParam.advanceFilter = e, $refs.table.refresh(true)}" />
						</template>
					</span>
			  </template>
				<template slot="toolForm" v-if="searchData.list.length">
					<a-form-item v-if="searchData.queryType === 'mergeQuery'">
						<a-input v-model="queryParam.mergeQuery" placeholder="请输入要搜索的条件" />
					</a-form-item>
					<template v-else-if="searchData.queryType === 'selectQuery' && searchData.upperLimit <= searchData.list.length">
						<a-form-item>
							<a-select allowClear style="width: 150px;" v-model="selectFiled">
								<a-select-option v-for="(item, index) in searchData.list" :key="item.filed">
									{{item.filedName}}
								</a-select-option>
							</a-select>
						</a-form-item>
						<a-form-item>
							<a-input v-model="queryParam[selectFiled]" placeholder="请输入要搜索的条件" />
						</a-form-item>
					</template>
					<a-form-item v-else v-for="(item, index) in searchData.list" :key="index">
						<template v-if="item.filedType === 'date'">
							<template v-if="item.type === 'range'">
								<a-range-picker
									v-model="rangeDate[item.filed]"
									:showTime="item.showTime"
									@change="(dates,dateStrings) => rangeQueryChange(dateStrings, item.filed)"
								/>
							</template>
							<template v-else>
								<t-date
									type="date"
								  :placeholder="item.filedName"
								  v-model="queryParam[item.filed]"
								/>
							</template>
						</template>
						<template v-else-if="item.filedType === 'time'">
							<t-date
								style="width: 183px;"
								type="time"
								dateFormat="HH:mm:ss"
							  :placeholder="item.filedName"
							  v-model="queryParam[item.filed]"
							/>
						</template>
						<template v-else-if="~['select', 'checkbox', 'radio', 'treeSelect'].indexOf(item.filedType)">
							<select-search :searchItem="item" :formJsonData="formJsonData" :type="item.filedType" v-model="queryParam[item.filed]" 
								:mode="item.filedType === 'checkbox' ? 'multiple' : 'default'"
								:saveCode="item.dataType == 'dynamic' ? getSaveCode(item.filed) : ''"
								:showCode="item.dataType == 'dynamic' ? getSaveCode(item.filed, 'showCode') : ''"
								@input="(e) => selectChange(e, item.filed)"></select-search>
						</template>
						<template v-else-if="item.filedType === 'userPop' || item.filedType === 'depart'">
							<component :is="objectKeys[item.filedType].compoent" :placeholder="`请选择${item.filedName}`"
							v-bind="objectKeys[item.filedType].attr" v-model="queryParam[item.filed]"></component>
						</template>
						<template v-else>
							<a-input v-model="queryParam[item.filed]" :placeholder="item.filedName" />
						</template>
					</a-form-item>
				</template>
			</tool-bar>
			<DataGrid v-if="columns.length > 0"
				ref="table"
				:columns="columns"
				:url="url"
				:queryParam="{...queryParam, ...queryParamDo}"
				rowKey="uuid"
				:scroll="scroll"
				:pageSize="showPageSize"
				:showPagination="showPage"
				:initLoad="initLoad"
			>
				<template :slot="item" slot-scope="{ text, record }" v-for="(item, index) in switchSlotName">
					<a-switch :checked="text == 'true'?true:false" disabled />
				</template>
				<template slot="renderAction" slot-scope="{ text, record }">
					<span v-for="(item, index) in lineButtonList" :key="index">
						<template v-if="item.permissionId">
							<a style="margin-right: 5px"
								:class="{'action-delete':item.name == '删除'}"
								v-if="item.checked"
								@click="handleBtnEvent(item, record, 'inline')"
								v-action="item.permissionId"
							>{{item.name}}</a>
						</template>
						<template v-else>
							<a style="margin-right: 5px"
								:class="{'action-delete':item.name == '删除'}"
								v-if="item.checked && item.btnType != 'print'"
								@click="handleBtnEvent(item, record, 'inline')"
							>{{item.name}}</a>
							<a-dropdown v-if="item.checked && item.btnType == 'print'">
								<a class="ant-dropdown-link">
									{{item.name}}<a-icon type="down" />
								</a>
								<a-menu slot="overlay">
									<a-menu-item v-for="(items, indexs) in item.list" :key="indexs">
										<a href="javascript:;" @click="handleBtnEvent(item, items, record)">{{ items | nameFilter }}</a>
									</a-menu-item>
								</a-menu>
							</a-dropdown>
						</template>
					</span>
				</template>
			</DataGrid>
			<edit-form
				ref="createModal"
				:visible="visible"
				:loading="confirmLoading"
				:url="url"
				:requestMethod="requestMethod"
				:tableDataType="tableDataType"
				:reportView="reportView"
        :isView="isView"
				@cancel="handleCancel()"
				@ok="handleOk()"
			/>

			<form-view
				ref="formViewModal"
				:visible="formViewVisible"
				@ok="() => formViewVisible = false"
				@cancel="() => formViewVisible = false"
			>
			</form-view>

		</div>
	</div>
</template>

<script>
	import { mapGetters } from 'vuex';
	import {
		DataGrid,
		DepartPopup, 
		PersonnelPopup
	} from "@/components";
	import {
		dataGridMixin
	} from "@/mixins/dataGridMixin";

	import editForm from "./edit.vue";
	import formView from "./formView.vue";
	import util from "@/utils/util";
	import {
		getColumns
	} from "@/utils/formatter";
	import CombinedQuery from "@/components/TopVUI/custom/CombinedQuery";
	import selectSearch from "../formPreview/selectSearch.vue";
	import { objToParam } from "@/utils/util";
	import { baseUrl } from "@/services/baseUrl.js";
	export default {
		name: "TableList",
		mixins: [dataGridMixin],
		components: {
			DataGrid,
			editForm,
			CombinedQuery,
			formView,
			selectSearch,
			PersonnelPopup,
			DepartPopup
		},
		props:{
			tableId : ''
		},
		provide() {
			// 使用函数的形式，可以访问到 `this`
			return {
				sameValue: false
			}
		},
		filters: {
			nameFilter(val) {
				if (val) {
					return val.replace('.ureport.xml', '')
				}
					return val;
			},
		},
		data() {
			return {
				id: `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`,
				visible: false,
				formViewVisible: false,
				confirmLoading: false,
				mdl: null,
				// 高级搜索 展开/关闭
				advanced: false,
				// 查询参数
				queryParam: {
					uuid: this.$route.meta.tableUuid,
					listDataType: "web"
				},
				selectedRowKeys: [],
				selectedRows: [],
				rows: "", //选中行数据
				columns: [],
				url: {
					getPageSet: "/form/formDatabase/formGetPageSet",
					save: "/form/formDatabase/formSave",
					update: "/form/formDatabase/formUpdate",
					deleteBatch: "/form/formDatabase/formDelete",
				},
				scroll: {},
				topButtonList: [],
				lineButtonList: [],
				searchData: {
					list: []
				},
				showPage: true,
				showPageSize: 20,
				formJsonData: "",
				interface: null,
				requestMethod: 'get',
				selectFiled: '',
				tableDataType: '', // 表数据类型，是自动生成还是选择表
				iconData: [{
					key: 'info',
					type: 'info-circle',
					twoToneColor: '#1890ff',
				},{
					key: 'success',
					type: 'check-circle',
					twoToneColor: '#52c41a'
				},{
					key: 'error',
					type: 'close-circle',
					twoToneColor: '#f5222d'
				},{
					key: 'warning',
					type: 'exclamation-circle',
					twoToneColor: '#faad14'
				},{
					key: 'confirm',
					type: 'question-circle',
					twoToneColor: '#faad14'
				}],
				drawingList: {},
				switchSlotName: [],
				rangeDate: [],
				formType: "",
				interfaceUuid: "",
				objectKeys: {
					userPop: {
						compoent: PersonnelPopup,
						attr:{
							style:{width: '183px'},
							multiple: false,
						},
					},
					depart: {
						compoent: DepartPopup,
						attr:{
							style: {width: '183px'},
						}
					},
				},
				queryParamDo: {},//处理后的搜索条件  对应于当为多选下拉情况
				database: null,
				reportView: {}, //报表预览
        isView: true,
				initLoad: false
			};
		},
		watch: {
			$route: function(newRoute, from) {
				this.queryParam.uuid = newRoute.query.tableUuid
				this.loadDataJson(newRoute.query.tableUuid);
			},
			selectFiled: {
				handler: function(newVal, oldVal){
					delete this.queryParam[oldVal]
				}
			}
		},
		computed:{
			...mapGetters(['userInfo']),
		},
		mounted() {
			if(this.tableId){
				this.queryParam.uuid = this.tableId;
				this.loadDataJson(this.tableId);
				return
			}
			this.queryParam.uuid = this.$route.query.tableUuid;
			this.loadDataJson(this.$route.query.tableUuid);
		},
		methods: {
			getSaveCode(filed, code = 'saveCode') {
				let list = JSON.parse(this.formJsonData).list
				let data = list.find((item) => item.key == filed)
				return data?.options[code]
			},
			// 获取数据
			loadDataJson(e) {
				this.columns = [];
				this.tableUuid = e;
				this.$post("/form/formBasicConfigure/getDetailByUuid", {
					uuid: this.tableUuid,
				}).then((res) => {
					this.formJsonData = res.formDesign.designJson;
					this.drawingList = JSON.parse(res.formList.webListJson);
					this.formType = res.formBasicConfigure.type;
					this.interfaceUuid = res.formBasicConfigure.interfaceUuid;
					this.database = JSON.parse(res.formDatabase.databaseJson)
					let hasPrint = this.drawingList.listProData.lineButtonList.find(item => item.btnType == 'print');
					if(!hasPrint){
						this.reportView.reportList = {list:[]}
						this.reportView.isView = false;
					}else{
						this.reportView.reportList = hasPrint
						this.reportView.isView = true;
					}
					this.reportView.database = this.database;
					if(this.formType !== "viewData"){
						this.tableDataType = res.formDatabase.type;
					}else{
						this.url.getPageSet = "/system/sysInterfaceManagement/formViewDataGetPageSet";
						this.queryParam.uuid = this.interfaceUuid;
					}
					this.switchSlotName = [];
					this.drawingList.listData.forEach((item,index) => {
						if(item.filed.split("_")[0] === "switch"){
							this.switchSlotName.push("switch"+index);
							this.columns.push({
								title: item.filedName,
								dataIndex: item.filed,
								align: item.align,
								width: item.width,
								fixed: item.fixed,
								sorter: item.sort,
								scopedSlots: { customRender: "switch"+index }
							})
						}else{
							this.columns.push({
								title: item.filedName,
								dataIndex: item.filed,
								align: item.align,
								width: item.width,
								fixed: item.fixed,
								sorter: item.sort
							})
						}
					});
					if(this.drawingList.listProData.lineButtonList.length && this.formType !== 'viewData'){
						this.columns.push({
							title: "操作",
							align: "center",
							dataIndex: "action",
							width: 200,
							scopedSlots: {
								customRender: "renderAction",
							},
							fixed: "right"
						})
					}
					// 行内按钮数据
					this.lineButtonList = this.drawingList.listProData.lineButtonList
					// 顶部按钮数据
					this.topButtonList = this.drawingList.listProData.topButtonList
					// 查询数据
					this.searchData.list = this.drawingList.searchData.list

					this.searchData.queryType = this.drawingList.searchData.queryType
					this.searchData.upperLimit = this.drawingList.searchData.upperLimit
					this.showPage = this.drawingList.listProData.showPage
					this.showPageSize = this.drawingList.listProData.showPageSize
					this.scroll.x = this.columns.length * 100
					
					// if (this.columns.length > 10) {
					// 	this.columns.splice(11);
					// }
					this.id = `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`
				});
			},
			// 新增
			handleAdd() {
				this.visible = true;
				this.$refs.createModal.title = "新增"
				this.$refs.createModal.loadData(
					this.$route.query.tableUuid,
					"add",
					this.formJsonData
				);
			},
			// 编辑
			handleEdit(record) {
				this.rows = record
				this.reportView.rowsUuid = record.uuid;
				if (this.rows) {
					this.visible = true;
					this.$refs.createModal.title = "编辑"
					this.$refs.createModal.loading = true
					this.$post("/form/formDatabase/formGetDetail", {
						uuid: record.uuid,
						formUuid: this.$route.query.tableUuid
					}).then((res) => {

						this.$refs.createModal.loadData(
							this.$route.query.tableUuid,
							"edit",
							this.formJsonData,
							res
						);
					});
				} else {
					this.$message.warn("请先选中需要修改的数据");
					return true;
				}
			},
			rowClassName(row) {
				return row.uuid === this.rows?.uuid ? "bg-bray" : ""; // 每条数据的唯一识别值
			},
			// 预览详情
			handleView(record) {
				this.rows = record
				if (this.rows) {
					this.visible = true;
					this.$refs.createModal.title = "详情"
					this.$refs.createModal.loading = true
					this.$post("/form/formDatabase/formGetDetail", {
						uuid: record.uuid,
						formUuid: this.$route.query.tableUuid
					}).then((res) => {
						this.$refs.createModal.loadData(
							this.$route.query.tableUuid,
							"view",
							this.formJsonData,
							res
						);
					});
				} else {
					this.$message.warn("请选中需要查看的数据");
					return true;
				}
			},
			handleOk: function() {
				this.visible = false;
				this.$refs.table.refresh();
			},
			// 删除
			handleSub(e, type) {
				const that = this;
				let uuids = "";
				if (that.$refs.table.selectedRowKeys.length === 0 && type != 'inline') {
					that.$message.warn("请勾选需要删除的数据");
					return;
				} else {
					uuids = that.$refs.table.selectedRowKeys.toString() || e.uuid;
				}
				that.$confirm({
					title: that.$ct("tips","提示"),
					content: that.$ct("deleteConfirmationPrompt","确定删除该数据吗？删除之后不可恢复！"),
					okText: that.$ct("confirm","确定"),
					cancelText: that.$ct("cancel","取消"),
					closable: true,
					icon: () => that.$createElement('a-icon', {
						props: {
							key: 'warning',
							type: 'exclamation-circle',
							twoToneColor: '#faad14'
						}
					}),
					onOk() {
						// 在这里调用删除接口
						that.$post(that.url.deleteBatch, {
							uuid: uuids,
							formUuid: that.$route.query.tableUuid,
						}).then((res) => {
							if (res.statusCode === 200 || res === 1) {
								that.$message.success("删除成功");
								that.rows = "";
								that.$refs.table.selectedRowKeys = [];
								that.$refs.table.refresh();
							} else {
								that.$message.error("删除失败");
							}
						});
					},
					onCancel() {},
				});
			},
			resetSearch(){
				this.selectFiled = "";
				this.rangeDate = [];
				this.queryParam = {
					uuid: this.$route.query.tableUuid,
					listDataType: "web"
				};
				this.queryParamDo = {
					...this.queryParam
				}
				this.$refs.table.refresh(true);
			},
			handleBtnEvent(options, record, type){
				this.requestMethod = options.requestMethod
				this.interface = options.interface || null // 接口地址
				if(options.btnType === 'add'){
					this.url.save = this.interface || this.url.save
					this.handleAdd()
				}else if(options.btnType === 'edit'){
					this.url.update = this.interface || this.url.update
					this.mdl = record
					this.handleEdit(record)
				}else if(options.btnType === 'delete'){
					this.url.deleteBatch = this.interface || this.url.deleteBatch
					this.handleSub(record, type)
				}else if(options.btnType === 'search'){

				}else if (options.btnType === 'print'){
					this.handlePrint(record, type)
					// record是报表名  type为record
					// console.log(options, record, type)
				}else if(options.newlyAdded){
					let param;
					let that = this;
					if(options.tableRowKey === 2){
						that.handleConfirm(that.interface, param, record, options)
					} else if(!record){
						that.$message.warn('请选择需要操作的数据', 1.5)
					}else{
						if(options.requestParam){
							param = {}
							let data = options.requestParam.split(",")
							data.forEach(item => {
								param[item.split(":")[0]] = record[item.split(":")[1]] || item.split(":")[1]
							})
						}
						if(options.showDialog){
							let obj = that.iconData.filter(item => item.key === options.messageIcon)[0]
							obj.theme = 'twoTone'
							that.$confirm({
								title: '操作提示',
								content: options.message || '确定要执行该操作吗？',
								okText: options.okText || '确定',
								okType: 'danger',
								cancelText: options.cancelText || '取消',
								icon: () => that.$createElement('a-icon', {
									props: obj
								}),
								onOk() {
									that.handleConfirm(that.interface, param, record, options)
								}
							})
						}else{
							let url = that.splicing(that.interface, param || record)
							that['$'+that.requestMethod](url, param || record).then(res => {
								if (res.statusCode === 200) {
									that.$refs.table.refresh()
									that.$message.success(res.message || '操作成功', 1.5)
								}else{
									that.$message.error(res.message || '操作失败', 1.5)
								}
							})
						}
					}
				}
			},
			handleConfirm(url, param, record, options){
				if(options.tableRowKey === 1){
					let requestUrl = this.splicing(url, param || record)
					this['$'+this.requestMethod](requestUrl, param || record).then(res => {
						if (res.statusCode === 200) {
							this.$refs.table.refresh()
							this.$message.success(res.message || '操作成功', 1.5)
						}else{
							this.$message.error(res.message || '操作失败', 1.5)
						}
					})
				}else if(options.tableRowKey === 2){
					// this.handleAdd()
					this.$refs.formViewModal.plugs = [];
					this.$refs.formViewModal.plugs.push((resolve) => require([`@/pages${options.formUrl}.vue`], resolve));
					this.$refs.formViewModal.drawingList = record;
					this.$refs.formViewModal.saveUrl = options.formSaveUrl;
					this.$refs.formViewModal.title = options.name;
					this.formViewVisible = true;
				}else if(options.tableRowKey === 3){
					let param = {
						...record,
						modelKey: options.flowModelKey,
						businessTitle: options.businessTitle + "-" + this.userInfo.userName,
					}
					param.businessUuid = param.uuid;
					delete param.uuid;
					this.$post("/workflow/apiFlowableProcessInstance/startProcessInstanceByKey", param).then(res => {
						if (res.status !== 300) {
						  this.$message.success("流程启动成功！", 1.5);
						} else {
						  this.$message.warn(res.message, 1.5);
						}
					})
				}
			},
			splicing(url, pramar){
				if(this.requestMethod === 'get' && url.indexOf("?") > -1){
					url = url + objToParam(pramar, '&') || ""
				}else if(this.requestMethod === 'get' && url.indexOf("?") === -1){
					url = url + objToParam(pramar)
				}
				return url
			},
			rangeQueryChange(dateStrings,filed){
				this.queryParam[filed] = JSON.stringify(dateStrings);
				this.rangeDate.push({
					[filed]: JSON.stringify(dateStrings)
				})
			},
			search() {
				this.$refs.table.refresh(true)
			},
			selectChange(e, filed) {
				this.queryParamDo[filed] = e.toString()
			},
			handlePrint(reportName, record) {
				let uuid = record.uuid
				this.$router.push(
				{
					path: '/report/preview',
					query: {
						url: `${baseUrl}/report/ureport/pdf/show?_u=mysql-${reportName}&uuid=${uuid}&tableName=${this.database.tableName}`
					}
				})
				// window.open(`${baseUrl}/report/ureport/pdf/show?_u=mysql-${reportName}&uuid=${uuid}&tableName=${this.database.tableName}`)
			}
		},
	};
</script>

<style lang="less" scoped="scoped">
	.table-operator button{
		margin-right: 8px;
	}
</style>
